# coding=utf-8


from os import path
from Effects_Library import Ui_MainWindow
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QVBoxLayout, QToolButton, QSizePolicy, QPushButton, \
    QGroupBox, QGridLayout
from PyQt5.QtGui import QIcon, QFont, QPixmap
from PyQt5.QtCore import QPoint, QRect, QSize, Qt  # , pyqtSignal
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets, QtCore
from PyQt5 import QtGui
# PySide2
# PyQt5
import sys
import os

#import maya.mel as mel
#from maya import OpenMayaUI as omui
#from shiboken2 import wrapInstance
#
#mayaMainWindowPtr = omui.MQtUtil.mainWindow()
#mayaMainWindow = wrapInstance(long(mayaMainWindowPtr), QWidget)  #


class mainWindow(Ui_MainWindow, QMainWindow):

    def __init__(self):
        super(mainWindow, self).__init__()
        #self.setParent(mayaMainWindow)  #
        #self.setWindowFlags(Qt.Window)
        self.setupUi(self)
        # super(mainWindow, self).setWindowFlags(QtCore.Qt.Window|QtCore.Qt.WindowStaysOnTopHint)
        self.Pic_Size = 140
        self.flowLayout = FlowLayout()
        self.Create_first_directory()

        self.treeWidget.header().setVisible(False)
        #self.treeWidget.setHeaderHidden(0)
        self.treeWidget.setStyleSheet('''#treeWidget::item{height:30px;}''')
        self.scrollArea.setWidgetResizable(True)
        self.pushButton.clicked.connect(self.ImportPic)

    def Create_first_directory(self):
        self.projcet = 'C:/Users/liujize/Desktop/aaa/TX'
        for  i in  os.listdir(self.projcet):
            o =  str(i)
            child1 = QTreeWidgetItem(self.treeWidget)

            child1.setText(0,i)
            '''
            if os.path.isdir(os.path.join(self.projcet,i)):
                for childPath2 in os.listdir(os.path.join(self.projcet,i)):
                    child2 = QTreeWidgetItem(child1)
                    child2.setText(0, childPath2)'''
        self.treeWidget.clicked.connect(self.TreeWidget_Clicked)


    def TreeWidget_Clicked(self, index):
        for i in range(self.flowLayout.count()):
            self.flowLayout.itemAt(i).widget().deleteLater()
        item = self.treeWidget.currentItem()
        FileClass = item.text(0)
        FileClassPath = os.path.join(self.projcet, FileClass)
        for PicName in os.listdir(FileClassPath):
            PicFilePath = os.path.join(FileClassPath, PicName)
            self.Create_button(PicFilePath)

    def showMenu(self, PicFilePath):
        self.button_menu = QMenu(self)
        self.actionA = QAction( self.button_menu)
        self.actionA.setText(u"打开文件夹")
        self.button_menu.addAction(self.actionA)
        self.actionA.triggered.connect(lambda *args: self.op_button(PicFilePath))  # 将动作A触发时连接到槽函数 button
        self.button_menu.popup(QCursor.pos())

    def op_button(self, PicFilePath):
        os.startfile(PicFilePath)

    def Create_button(self,PicFilePath):
        self.button = MyBtn()
        #self.button = QToolButton()FR
        self.button.setToolButtonStyle(Qt.ToolButtonStyle(0))
        #self.button.setText(PicFilePath)
        self.button.setObjectName(PicFilePath)
        self.button.setCheckable(True)
        self.button.setChecked(False)
        self.button.setAutoRepeat(True)
        self.button.setAutoExclusive(True)
        self.button.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)  # 使用customContextMenuRequested 必须要设置这行代码
        self.button.customContextMenuRequested.connect(lambda *args: self.showMenu(PicFilePath))

        self.flowLayout.addWidget(self.button)

        #获取图片完整路径
        for  PicPng in os.listdir(PicFilePath):
            if os.path.isfile(PicFilePath + "/"+PicPng):
                #print(PicFilePath + "/"+PicPng)
                img = QtGui.QImage(PicFilePath + "/"+PicPng)  # 这里图片路径可以不给格式：QtGui.QImage(r'd:/test')
                pixmap = QtGui.QPixmap(img)
                fitPixmap = pixmap.scaled(self.Pic_Size, self.Pic_Size, QtCore.Qt.IgnoreAspectRatio, QtCore.Qt.SmoothTransformation)  # 注意 scaled() 返回一个 QtGui.QPixmap
                icon = QtGui.QIcon(fitPixmap)
                self.button.setIcon(icon)
                self.button.setIconSize(QtCore.QSize(self.Pic_Size, self.Pic_Size))
                self.listWidget.setLayout(self.flowLayout)

        self.button.clicked.connect(lambda *args: self.setcoonton(PicFilePath))

    def setcoonton(self, PicFilePath):
        self.Pic_Path = PicFilePath
        self.PicLens(os.listdir(PicFilePath))
        '''
        self.n = 0
        if self.n != 0:
            self.n == 0
        self.Timerrange = 50
        self.timer1 = QTimer()
        self.timer1.start(self.Timerrange)
        self.timer1.timeout.connect(lambda *args: self.timer_TimeOut(PicFilePath))
        self.PicLens(os.listdir(PicFilePath))
'''
    def timer_TimeOut(self, PicFilePath):
        files = os.listdir(PicFilePath)
        if self.n < len(files):
            self.n = self.n + 1
        if self.n == len(files):
            self.n = 0
        #self.label.setPixmap(QPixmap(PicFilePath + "/" + files[self.n]))
        #self.label.setScaledContents(True)
        #self.label.setFixedHeight(200)
        #self.label.setFixedWidth(200)



    def PicLens(self,files):
        self.Range_label_TxT.setText(str(len(files)))

    def ImportPic(self):
        pic = os.listdir(self.Pic_Path)
        Pic_Name = self.Pic_Path.split("/")[-1]
        ImgFilePath = self.Pic_Path + '/' + pic[0]
        # File = os.path.basename(ImgFilePath)
        PicPolyLens = []
        List_AllTransform = cmds.ls(transforms=1)
        for List_PolyS in List_AllTransform:
            if Pic_Name in List_PolyS:
                for Polys in cmds.listHistory(List_PolyS):
                    if 'polyPlane' in Polys:
                        PicPolyLens.append(Polys)
        Pic_version = ''
        for i in range(len(PicPolyLens)):
            if i + 1 == len(PicPolyLens):
                Pic_version = str(i + 1)

        polyP = cmds.polyPlane(n=Pic_Name + Pic_version, sx=1, sy=1)

        main_A =  cmds.circle(n=Pic_Name + '_main_A' + Pic_version, nr=[0, 1, 0], sw=360, d=3, r=1.5, ut=0, ch=0, tol=0.01)[0]
        main_B = cmds.circle(n=Pic_Name + '_main_B' + Pic_version, nr=[0, 1, 0], sw=360, d=3, r=1, ut=0, ch=0, tol=0.01)[0]
        polyP_Grp = cmds.group(em=True, name=Pic_Name + '_Grp' + Pic_version)

        cmds.parent(main_B, main_A)
        cmds.parentConstraint(main_B, polyP[0])
        cmds.scaleConstraint(main_B, polyP[0], mo=1, weight=1)

        cmds.setAttr(polyP[0] + ".tx", lock=1)
        cmds.setAttr(polyP[0] + ".ty", lock=1)
        cmds.setAttr(polyP[0] + ".tz", lock=1)
        cmds.setAttr(polyP[0] + ".rx", lock=1)
        cmds.setAttr(polyP[0] + ".ry", lock=1)
        cmds.setAttr(polyP[0] + ".rz", lock=1)
        cmds.setAttr(polyP[0] + ".sx", lock=1)
        cmds.setAttr(polyP[0] + ".sy", lock=1)
        cmds.setAttr(polyP[0] + ".sz", lock=1)
        cmds.setAttr(polyP[0] + ".v", lock=1)

        cmds.parent(polyP[0], main_A, polyP_Grp)

        CvMin = '|' + polyP_Grp + '|' + main_A
        cmds.addAttr(CvMin, ln='ShiJianPanYi', at='long', dv=0)
        cmds.setAttr(CvMin + '.ShiJianPanYi', e=1, keyable=1)

        cmds.addAttr(CvMin, ln='BaoGuang', at='float', min=-5, max=5, dv=0)
        cmds.setAttr(CvMin + '.BaoGuang', e=1, keyable=1)

        cmds.addAttr(CvMin, ln='TouMingTongDao', at='float', min=0, max=2, dv=1)
        cmds.setAttr(CvMin + '.TouMingTongDao', e=1, keyable=1)

        cmds.addAttr(CvMin, ln='ColorGainR', at='float', min=0, max=20, dv=0)
        cmds.setAttr(CvMin + '.ColorGainR', e=1, keyable=1)
        cmds.addAttr(CvMin, ln='ColorGainG', at='float', min=0, max=20, dv=0)
        cmds.setAttr(CvMin + '.ColorGainG', e=1, keyable=1)
        cmds.addAttr(CvMin, ln='ColorGainB', at='float', min=0, max=20, dv=0)
        cmds.setAttr(CvMin + '.ColorGainB', e=1, keyable=1)

        lambertName = cmds.shadingNode('lambert', asShader=True, n=polyP[0] + '_labt')
        lambertSG = cmds.sets(renderable=1, noSurfaceShader=1, empty=1, name=polyP[0] + '_SG')
        cmds.connectAttr(lambertName + '.outColor', lambertSG + '.surfaceShader', f=1)
        cmds.sets(polyP[0], e=1, forceElement=lambertSG)
        shadingNodefile = cmds.shadingNode('file', asTexture=1, isColorManaged=1, n=polyP[0] + '_file')
        cmds.connectAttr(shadingNodefile + '.outColor', lambertName + '.color', f=1)

        TextureName = cmds.shadingNode('place2dTexture', asUtility=1, n=polyP[0] + '_Texture')
        Nodes = ['coverage', 'translateFrame', 'rotateFrame', 'mirrorU', 'mirrorV', 'stagger', 'wrapU',
                 'wrapV', 'repeatUV', 'offset', 'rotateUV', 'noiseUV', 'vertexUvOne', 'vertexUvTwo',
                 'vertexUvThree', 'vertexCameraOne']
        for Node in Nodes:
            cmds.connectAttr(TextureName + '.' + Node, shadingNodefile + '.' + Node, f=1)
        cmds.connectAttr(TextureName + '.outUV', shadingNodefile + '.uv')
        cmds.connectAttr(TextureName + '.outUvFilterSize', shadingNodefile + '.uvFilterSize')

        cmds.setAttr(shadingNodefile + '.fileTextureName', ImgFilePath, type="string")
        cmds.defaultNavigation(force=1, connectToExisting=1, source=shadingNodefile, destination=lambertName + '.color')
        cmds.connectAttr(shadingNodefile + '.outTransparency', lambertName + '.transparency', f=1)
        cmds.select(shadingNodefile, r=1)
        # 璐村浘婊氬姩

        visible = cmds.workspaceControl('AttributeEditor', q=1, visible=1)
        if visible:
            cmds.workspaceControl('AttributeEditor', e=1, close=1)

        mel.eval("ToggleAttributeEditor")

        cmds.setAttr(shadingNodefile + ".useFrameExtension", 1)

        cmds.connectAttr(main_A + '.ShiJianPanYi', shadingNodefile + '.io', f=1)
        cmds.connectAttr(main_A + '.BaoGuang', shadingNodefile + '.exp', f=1)
        cmds.connectAttr(main_A + '.TouMingTongDao', shadingNodefile + '.ag', f=1)

        cmds.connectAttr(main_A + '.ColorGainR', shadingNodefile + '.cor', f=1)
        cmds.connectAttr(main_A + '.ColorGainG', shadingNodefile + '.cog', f=1)
        cmds.connectAttr(main_A + '.ColorGainB', shadingNodefile + '.cob', f=1)
        cmds.evalDeferred('mel.eval("ToggleChannelsLayers")')

class labo(QToolButton):
    def __init__(self):
        super(labo, self).__init__()
        self.Btn = super(labo, self)

    def enterEvent(self, a0):
        print('888888888888888888')

    def leaveEvent(self, a0):
        print('999999999999999999')
# 获取鼠标事件
class MyBtn(QToolButton):
    def __init__(self):
        super(MyBtn, self).__init__()
        self.Btn = super(MyBtn, self)
        #self.setParent(mayaMainWindow)  # 灏嗘柊绐楀彛璁剧疆涓簃aya鐨勫瓙绾?
        #self.setWindowFlags(Qt.Window)
        self.Pic_Size = 140
        self.Pic_ControlSize = 170


    '''
    def mouseMoveEvent(self, e):
        print("ok")

    def mousePressEvent(self, e):
        print("Not Ok")'''

    def enterEvent(self, a0):
        self.setcoonton()
        return (self.Btn.enterEvent(a0))

    def leaveEvent(self, a0):
        files = os.listdir(self.Btn.objectName())
        img = QtGui.QImage(self.Btn.objectName() + "/" + files[self.n])  # 这里图片路径可以不给格式：QtGui.QImage(r'd:/test')
        pixmap = QtGui.QPixmap(img)
        fitPixmap = pixmap.scaled(self.Pic_Size, self.Pic_Size, QtCore.Qt.IgnoreAspectRatio,QtCore.Qt.SmoothTransformation)  # 注意 scaled() 返回一个 QtGui.QPixmap
        icon = QtGui.QIcon(fitPixmap)
        self.Btn.setIcon(icon)
        self.Btn.setIconSize(QtCore.QSize(self.Pic_Size, self.Pic_Size))
        # super().setFixedHeight(140)
        # super().setFixedWidth(140)
        self.timer1.stop()
        return self.Btn.leaveEvent(a0)

    def setcoonton(self):
        #print(self.Btn.objectName())
        #self.Pic_Path = two_Level_path
        self.n = 0
        if self.n != 0:
            self.n == 0
        self.Timerrange = 50
        self.timer1 = QTimer()
        self.timer1.start(self.Timerrange)
        self.timer1.timeout.connect(lambda *args: self.timer_TimeOut(self.Btn.objectName()))

    def timer_TimeOut(self, two_Level_path):
        files = os.listdir(two_Level_path)
        if self.n < len(files):
            self.n = self.n + 1
        if self.n == len(files):
            self.n = 0

        img = QtGui.QImage(two_Level_path + "/" + files[self.n])  # 这里图片路径可以不给格式：QtGui.QImage(r'd:/test')
        pixmap = QtGui.QPixmap(img)
        fitPixmap = pixmap.scaled(self.Pic_ControlSize, self.Pic_ControlSize, QtCore.Qt.IgnoreAspectRatio,QtCore.Qt.SmoothTransformation)  # 注意 scaled() 返回一个 QtGui.QPixmap
        icon = QtGui.QIcon(fitPixmap)
        self.Btn.setIcon(icon)
        self.Btn.setIconSize(QtCore.QSize(self.Pic_ControlSize, self.Pic_ControlSize))

    # super().setIcon(QIcon(two_Level_path + "/" + files[self.n]))
    # super().setIconSize(QtCore.QSize(200, 200))
    ##super().setScaledContents(True)
    # super().setFixedHeight(200)
    # super().setFixedWidth(200)


class FlowLayout(QLayout):
    def __init__(self, parent=None, margin=0, spacing=-1):
        super(FlowLayout, self).__init__(parent)

        if parent is not None:
            self.setContentsMargins(margin, margin, margin, margin)

        self.setSpacing(spacing)

        self.itemList = []

    def __del__(self):
        item = self.takeAt(0)
        while item:
            item = self.takeAt(0)

    def addItem(self, item):
        self.itemList.append(item)

    def count(self):
        return len(self.itemList)

    def clear(self):  # real signature unknown; restored from __doc__
        """ clear(self) -> None """
        self.itemList.clear()

    def itemAt(self, index):
        if index >= 0 and index < len(self.itemList):
            return self.itemList[index]

        return None

    def deleteLater(self):  # real signature unknown; restored from __doc__
        """ deleteLater(self) """
        pass

    def takeAt(self, index):
        if index >= 0 and index < len(self.itemList):
            return self.itemList.pop(index)

        return None

    def expandingDirections(self):
        return Qt.Orientations(Qt.Orientation(0))

    def hasHeightForWidth(self):
        return True

    def heightForWidth(self, width):
        height = self.doLayout(QRect(0, 0, width, 0), True)
        return height

    def setGeometry(self, rect):
        super(FlowLayout, self).setGeometry(rect)
        self.doLayout(rect, False)

    def sizeHint(self):
        return self.minimumSize()

    def minimumSize(self):
        size = QSize()

        for item in self.itemList:
            size = size.expandedTo(item.minimumSize())

        margin, _, _, _ = self.getContentsMargins()

        size += QSize(2 * margin, 2 * margin)
        return size

    def doLayout(self, rect, testOnly):
        x = rect.x()
        y = rect.y()
        lineHeight = 0

        for item in self.itemList:
            wid = item.widget()
            spaceX = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton,
                                                                QSizePolicy.PushButton, Qt.Horizontal)
            spaceY = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton,
                                                                QSizePolicy.PushButton, Qt.Vertical)
            nextX = x + item.sizeHint().width() + spaceX
            if nextX - spaceX > rect.right() and lineHeight > 0:
                x = rect.x()
                y = y + lineHeight + spaceY
                nextX = x + item.sizeHint().width() + spaceX
                lineHeight = 0

            if not testOnly:
                item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))

            x = nextX
            lineHeight = max(lineHeight, item.sizeHint().height())

        return y + lineHeight - rect.y()
'''
def main():
    app = QApplication([]) if not QApplication.instance() else None
    MWin = mainWindow()
    for qt in QApplication.topLevelWidgets():
        if qt.windowTitle() == u'MainWindow':
            qt.close()
    MWin.show()
    app.exec_() if app else None
    #sys.exit(app.exec())
if __name__ == "__main__":
    main()
'''
#客户端默认
'''   
if __name__ == '__main__':
    app = QApplication(sys.argv)
    MWin = mainWindow()
    MWin.show()
    sys.exit(app.exec())
'''
#Maya 客户端 通用

if __name__ == '__main__':
    app = QApplication([]) if not QApplication.instance() else None
    MWin = mainWindow()
    for qt in QApplication.topLevelWidgets():
        if qt.windowTitle() == u'MainWindow':
            qt.close()
    MWin.show()
    app.exec_() if app else None



